package cc.customer.authorization.resolvers;


import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import cc.customer.authorization.Constants;
import cc.customer.authorization.annotation.CurrentUser;

/**
 * 将含有CurrentUser注解的方法参数注入当前登录用户
 * @author Wang
 */
@Component
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
	
	@Autowired
    UserService userService;

    /**
     * 支持参数的条件：如果参数类型是User并且有CurrentUser注解
     */
	@Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.getParameterType().isAssignableFrom(MyUser.class) && parameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }

    /**
     * 取出鉴权时存入HttpRequest的登录用户Id，从数据库中查询用户信息并返回
     */
	@Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String currentUserId = (String) webRequest.getAttribute(Constants.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
        if (currentUserId != null) {
        	return userService.selectByKey(Long.parseLong(currentUserId));
        }
        throw new MissingServletRequestPartException(Constants.CURRENT_USER_ID);
    }
    
}
